#!/usr/bin/env python
# coding: utf-8

import sys
import threading
import schedule

reload(sys)
sys.setdefaultencoding('utf-8')
from wxbot import *


class MyWXBot(WXBot):
    jsSend = False
    i = 0

    def handle_msg_all(self, msg):
        if msg['msg_type_id'] == 4 and msg['content']['type'] == 12:
            content = msg['content']['data']
            if u'开启了朋友验证' in content:
                self.i = self.i + 1
                name = "A_" + str(self.i) + "_僵尸粉"
                self.updateFriendRemark(name, msg["user"]["id"])

    def contactCallback(self):
        # 如果没有发送过,保证只发送一次
        if self.jsSend == False:
            self.jsSend = True
            file_object = open(unicode(cur_file_dir() + "/img/僵尸粉检测消息.txt", "utf8"))
            try:
                text1 = file_object.read()
            finally:
                file_object.close()
            # 通讯录获取完成以后,发送僵尸粉检测消息
            for k, v in enumerate(self.contact_list):
                self.send_msg_by_uid(text1, v["UserName"])
                time.sleep(2)

    # 初始化3分钟后退出程序
    def initSchedule(self):
        job_thread = threading.Thread(target=self.job_func)
        job_thread.start()

    def job_func(self):
        schedule.every(180).seconds.do(self.job)
        while True:
            schedule.run_pending()
            time.sleep(10)

    def job(self):
        os.system("kill -9 " + str(os.getpid()))


def main():
    macImgName = sys.argv[1]
    isOpenImg = False
    bot = MyWXBot()
    bot.DEBUG = True
    bot.conf['qr'] = 'png'
    bot.initSchedule()
    bot.run(macImgName, isOpenImg)


if __name__ == '__main__':
    main()
